package com.hg.util.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;










import com.google.gson.Gson;
import com.hg.admin.service.AdminService;
import com.hg.cache.FIFOCache;
import com.hg.forSearch.db.dto.ForSearchDTO;
import com.hg.forSearch.service.ForSearchService;
import com.hg.util.common.Common;
import com.hg.util.http.CookieHelper;
import com.hg.util.http.FreemarkerUtils;
import com.hg.util.http.HttpXmlClient;

import freemarker.template.Configuration;

public class MbaseAction
{
	public Gson gson = new Gson();
	public Map<String, Object> map = new HashMap<String, Object>();
	ActionJspInvoker jsp = new ActionJspInvoker();
	public HttpXmlClient hxc = new HttpXmlClient();	//专门用于通过http方式向其他系统获取数据
	
	
	/**
	 * 从内存中获取数据库的缓存
	 * @param root
	 * @return
	 */
	public Map<String,String> getConfigForAdmin(Map root){
		FIFOCache<String, Object> cache = (FIFOCache<String, Object>) root.get("cache");
		Map<String,String> m_config=(Map<String, String>) cache.get("m_config");
		
		if(null==m_config){
			ForSearchService forS = new ForSearchService();
			
			List<ForSearchDTO> list=forS.getAll("hh_base_m_config_search");
			m_config= new HashMap<String,String>();
			for(int i=0;i<list.size();i++){
				ForSearchDTO dto = list.get(i);
				m_config.put(dto.getId(), dto.getName());
			}
			
			cache.put("m_config", m_config);
		}
		
		return m_config;
	}
	
	public void initLogin(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		
		HttpSession session = request.getSession();
		
		session.invalidate();
		session = request.getSession();
		
		String username = (String) root.get("username");
		String userId = root.get("userId")+"";
		String admin_role_id = root.get("admin_role_id")+"";
		session.setMaxInactiveInterval(60*60*4);
		session.setAttribute("username",root.get("username")+"");
		session.setAttribute("userId",root.get("userId")+"");
		session.setAttribute("admin_role_id", admin_role_id);
		try
		{
			username = URLEncoder.encode(username, "utf-8");
			userId = URLEncoder.encode(userId, "utf-8");
			CookieHelper.setCookie(response, "760FA3D2_C30F13FC", username);
			CookieHelper.setCookie(response, "75DD699F_3CC18466", userId);
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 检查是否已经登录
	 * @param request
	 * @return
	 */
	public boolean checkAdminLogin(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		
		HttpSession session = request.getSession();
		Cookie usercookie = CookieHelper.getCookie(request, "760FA3D2_C30F13FC");
		Cookie idcookie = CookieHelper.getCookie(request, "75DD699F_3CC18466");
		if(usercookie!=null && idcookie!=null){
			String cookie_user_name=null;
			String cookie_id=null;
			try
			{
				cookie_user_name = URLDecoder.decode(usercookie.getValue(), "UTF-8");
				cookie_id = URLDecoder.decode(idcookie.getValue(), "UTF-8");
				
				String user = (String)session.getAttribute("username");
				String id = session.getAttribute("userId")+"";
				
				if(user!=null && id!=null){
					if(user.equals(cookie_user_name) && id.equals(cookie_id)){
						return true;
					}
				}else{
					AdminService as = new AdminService();
					if(as.checkAdmin(cookie_id, cookie_user_name)){
						root.put("username", cookie_user_name);
						root.put("userId", cookie_id);
						initLogin(root);
						return true;
					}else{
						return false;
					}
				}
			}
			catch (UnsupportedEncodingException e)
			{
				e.printStackTrace();
			}
		}
		
		return false;
	}
	
	/**
     * 验证后台用户是否己经登录.
     *
     * @return true 或 false，分别表示用户是否己经登录。
     */
    public boolean isLogin(HttpServletRequest request) {
    	HttpSession session = request.getSession();
    	
    	String username=(String) session.getAttribute("username");
    	if(username==null){
    		//没有登录
    		return false;
    	}else{
    		return true;
    	}
    }
	
	/**
	 * 
	 * @param root servlet传递过来的集合
	 * @param module	模块名
	 * @param action	动作名
	 * @param params	参数
	 * @return
	 */
	public String getUrl(Map root, String module,String action,Map<String ,String> params){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		String url = Common.getProjectUrl(request)+"/"+root.get("folder_name")+"/"+module+"/"+action+".do";
		
		if(null!=params){
			url=url+"?"+Common.formatQueryParaMap(params, true);
		}
		
		return url;
	}
	
	/**
	 * 
	 * @param root servlet传递过来的集合
	 * @param action
	 * @param params
	 * @return
	 */
	public String getUrl(Map root,String action,Map<String ,String> params){
		String module=(String) root.get("module");
		return this.getUrl(root, module, action, params);
	}
	
	/**
	 * 
	 * @param root servlet传递过来的集合
	 * @param action
	 * @return
	 */
	public String getUrl(Map root,String action){
		String module=(String) root.get("module");
		Map<String ,String> params=null;
		return this.getUrl(root, module, action, params);
	}
	
	/**
	 * 完全自定义模板位置
	 * @param root
	 * @param tpl_url	WEB-INF/ftl/
	 * @param folder_name	admins
	 * @param module
	 * @param action
	 */
	public void ftl_return(Map root,String tpl_url,String folder_name,String module,String action){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		
		Configuration cfg= new Configuration();
		cfg.setServletContextForTemplateLoading(request.getSession()
				.getServletContext(), tpl_url+folder_name);		//"WEB-INF/templates/admin"
		//配置信息
		cfg.setNumberFormat("0.#");
		cfg.setDateFormat("yyyy-MM-dd");
		cfg.setTimeFormat("HH:mm:ss");
		cfg.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
		cfg.setOutputEncoding("UTF-8");
		cfg.setDefaultEncoding("UTF-8");
		//cfg.setClassicCompatible(true);		//这个配置会引起模板引入的报错
		//cfg.setTemplateUpdateDelay(2);
		//cfg.setLocale("zh_CN");
		//cfg.setTagSyntax("setTagSyntax");
		/*try
		{
			cfg.setSettings(Fs.getProperties("freemarker.properties"));
		}
		catch (TemplateException e)
		{
			e.printStackTrace();
		}*/
		FreemarkerUtils.freemarker(request, response,module+"/"+action+".ftl", cfg, root);
	}
	
	/**
	 * 模板位置采用默认的
	 * @param root
	 */
	public void ftl_return(Map root){
		String tpl_url =(String) root.get("tpl_url");
		String folder_name =(String) root.get("folder_name");
		String module =(String) root.get("module");
		String action =(String) root.get("action");
		this.ftl_return(root, tpl_url, folder_name, module, action);
	} 
	
	/**
	 * 自定义action文件名
	 * @param root
	 * @param action
	 */
	public void ftl_return(Map root,String action){
		String tpl_url =(String) root.get("tpl_url");
		String folder_name =(String) root.get("folder_name");
		String module =(String) root.get("module");
		this.ftl_return(root, tpl_url, folder_name, module, action);
	} 
	
	/**
	 * 完全自定义模板位置
	 * @param root
	 * @param tpl_url	WEB-INF/ftl/
	 * @param folder_name	admins
	 * @param module
	 * @param action
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void jsp_return(Map root,String tpl_url,String folder_name,String module,String action){
		HttpServletRequest req = (HttpServletRequest) root.get("request");
		HttpServletResponse res = (HttpServletResponse) root.get("response");
		String view =tpl_url+folder_name+"/"+module+"/"+action+".jsp";
		jsp.invoke(view, req, res);
	}
	
	/**
	 * 模板位置采用默认的
	 * @param root
	 */
	public void jsp_return(Map root){
		String tpl_url =(String) root.get("tpl_url");
		String folder_name =(String) root.get("folder_name");
		String module =(String) root.get("module");
		String action =(String) root.get("action");
		this.jsp_return(root, tpl_url, folder_name, module, action);
	} 
	
	/**
	 * 自定义action文件名
	 * @param root
	 * @param action
	 */
	public void jsp_return(Map root,String action){
		String tpl_url =(String) root.get("tpl_url");
		String folder_name =(String) root.get("folder_name");
		String module =(String) root.get("module");
		this.jsp_return(root, tpl_url, folder_name, module, action);
	} 
	
	/**
	 * @param root	servlet传递过来的那个Map root对象
	 * @param data	需要返回前端的数据,一般是Map 集合
	 * @throws IOException
	 */
	public void json_return(Map root,Object data){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		PrintWriter out=null;
		try
		{
			out = response.getWriter();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		out.write(gson.toJson(data));
		out.flush();
		out.close();
	}
	
	/**
	 * TODO 暂时没完成
	 * @param root	servlet传递过来的那个Map root对象
	 * @param data	需要返回前端的数据,一般是Map 集合
	 * @throws IOException
	 */
	public void jsonp_return(Map root,Object data){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		PrintWriter out=null;
		try
		{
			out = response.getWriter();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		String jsonp=request.getParameter("jsonpcallback"); 
		String return_str = jsonp+"("+gson.toJson(data)+")";  
		
		out.write(return_str);
		out.flush();
		out.close();
	}
	
	/**
	 * 返回字符串
	 * @param root
	 * @param data
	 */
	public void string_return(Map root,String data){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		PrintWriter out=null;
		try
		{
			out = response.getWriter();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		out.write(data);
		out.flush();
		out.close();
	}
	
	/**
	 * mk_eq.user_name  等于
	 * mk_gt.user_name	大于
	 * mk_gte.user_name	大于等于
	 * mk_lt.user_name	小于
	 * mk_lte.user_name	小于等于
	 * mk_like.user_name	like
	 * 获取查询的对象Args
	 * @param root
	 * @param rows	默认返回的行数
	 * @param default_sort 默认排序
	 * @return
	 */
	public Map<String, Object> getSearchArgs(Map root,int pageSize,String default_sort){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		
		Map<String, Object> args_data = new HashMap<String, Object>();		
		String page = request.getParameter("page"); //第几页
		String rows = request.getParameter("rows"); //没有多少行
		if(null==page || "".equals(page)){
			args_data.put("absPage", 1);
		}else{
			args_data.put("absPage", Integer.parseInt(page));
		}
		
		if(null==rows || "".equals(rows)){
			args_data.put("pageSize", pageSize);
		}else{
			args_data.put("pageSize", Integer.parseInt(rows));
		}
		
		
		StringBuffer sb = new StringBuffer();
		sb.append("1=1");
		
		Enumeration<String> qs = request.getParameterNames();
		while (qs.hasMoreElements()) {
			String s = qs.nextElement();
			
			if(s.startsWith("mk_eq")){	//等于
				String s1[] = s.substring("mk_eq".length()).split("\\.");
				String name = s1[1];
				sb.append(" and "+name+"='"+request.getParameter(s)+"'");
			}else if(s.startsWith("mk_like")){	//like
				String s1[] = s.substring("mk_like".length()).split("\\.");
				String name = s1[1];
				sb.append(" and "+name+" like '%"+request.getParameter(s)+"%'");
			}else if(s.startsWith("mk_gte")){	//大于等于
				String s1[] = s.substring("mk_gte".length()).split("\\.");
				String name = s1[1];
				sb.append(" and "+name+">='"+request.getParameter(s)+"'");
			}else if(s.startsWith("mk_lte")){
				String s1[] = s.substring("mk_lte".length()).split("\\.");
				String name = s1[1];
				sb.append(" and "+name+"<='"+request.getParameter(s)+"'");
			}else if(s.startsWith("mk_gt")){	//大于
				String s1[] = s.substring("mk_gt".length()).split("\\.");
				String name = s1[1];
				sb.append(" and "+name+">'"+request.getParameter(s)+"'");
			}else if(s.startsWith("mk_lt")){
				String s1[] = s.substring("mk_lt".length()).split("\\.");
				String name = s1[1];
				sb.append(" and "+name+"<'"+request.getParameter(s)+"'");
			}
	     }
		
		//获取排序的数据
		String sort_str= request.getParameter("sort");
		String order_str= request.getParameter("order");
		
		if(null!=sort_str && !"".equals(sort_str)){
			String[] sort = sort_str.split(",");
			String[] order = order_str.split(",");
			if(sort.length==1){
				sb.append(" order by "+sort[0]+" "+order[0]);
			}else if(sort.length>1){
				sb.append(" order by ");
				for(int i=0;i<sort.length;i++){
					sb.append(sort[i]+" "+order[i]);
					if(i!=sort.length-1){
						sb.append(",");
					}
				}
			}
		}else{
			sb.append(default_sort);
		}
		
		args_data.put("filter", sb.toString());
		return args_data;
	}
	
	/**
	 * @param root	servlet传递过来的那个Map root对象
	 * @param data	需要返回前端的数据,一般是Map 集合
	 * @throws IOException
	 */
	public void js_redirect(Map root,String url){
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		PrintWriter out=null;
		try
		{
			out = response.getWriter();
			out.println("<script>window.location.href='"+url+"';</script>");
			out.flush();
			out.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			out.flush();
			out.close();
		}
		
	}
	
	/**
	 * 管理员端退出以后的初始化
	 * @param vo
	 */
	public void initLogout(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		HttpServletResponse response = (HttpServletResponse) root.get("response");
		HttpSession session = request.getSession();
		
		session.setAttribute("username", null);
		session.setAttribute("userId", null);
		session.setAttribute("admin_role_id", null);
		CookieHelper.removeCookie(response, CookieHelper.getCookie(request, "760FA3D2_C30F13FC"));
		CookieHelper.removeCookie(response, CookieHelper.getCookie(request, "75DD699F_3CC18466"));
	}
	
	/**
	 * 把前端接收的参数转化成SortedMap<String, String>
	 * @param request
	 * @return
	 */
	public SortedMap<String, String> getSendParam(Map root){
		HttpServletRequest request = (HttpServletRequest) root.get("request");
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		
		Map<String, String[]> param_arr= request.getParameterMap();
		Set es = param_arr.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String[] v = (String[]) entry.getValue();
			StringBuilder sb = new StringBuilder();
			for(int i=0;i<v.length;i++){
				sb.append(","+v[i]);
			}
			packageParams.put(k, sb.toString().substring(1));
		}
		
		return packageParams;
	}	
}
